package com.lt.accesscontrolmanager.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service

public class OssService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    public String uploadFile(MultipartFile file) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            System.out.println(endpoint+"和"+accessKeySecret+"和"+accessKeyId);
            // 获取文件名并生成唯一的文件名
            String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
            //文件夹名
            String folderName = "acm/"; // 文件夹名称

            // 上传文件到指定的存储桶
            ossClient.putObject(bucketName, folderName+fileName, file.getInputStream());
            // 获取文件的访问URL
            return "https://" + bucketName + "." + endpoint + "/" + folderName+fileName;
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败", e);
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }

    public void deleteFile(String fileUrl) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            String objectName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            ossClient.deleteObject(bucketName, objectName);
        } finally {
            ossClient.shutdown();
        }
    }
}
